package com.atguigu.spzx.manner.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.spzx.manner.mapper.CategoryMapper;
import com.atguigu.spzx.manner.service.CategoryService;

import com.atguigu.spzx.manner.util.CategoryExcelListener;
import com.atguigu.spzx.model.entity.Category;
import com.atguigu.spzx.model.vo.CategoryExcelVo;
import jakarta.servlet.http.HttpServletResponse;
import lombok.SneakyThrows;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public List<Category> findByParentId(Long parentId) {
        List<Category> list = categoryMapper.findByParentId(parentId);
        for (Category category : list) {
            Long count = categoryMapper.countByParentId(category.getId());
            if (count == 0) {
                category.setHasChildren(false);
            } else {
                category.setHasChildren(true);
                category.setChildren(categoryMapper.findByParentId(category.getId()));
            }
        }
        return list;
    }

    @SneakyThrows
    @Override
    public void exportData(HttpServletResponse response) {

        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("商品分类.xlsx", StandardCharsets.UTF_8);
        // 设置 Content-disposition 响应头，指定文件作为附件下载并设置文件名
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        // 暴露 Content-Disposition 响应头，允许跨域访问
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        List<Category> categories = categoryMapper.selectAll();
        ArrayList<CategoryExcelVo> categoryExcelVos = new ArrayList<>();
        for (Category category : categories) {
            CategoryExcelVo categoryExcelVo = new CategoryExcelVo();
            BeanUtils.copyProperties(category, categoryExcelVo);
            categoryExcelVos.add(categoryExcelVo);
        }
        EasyExcel.write(response.getOutputStream(), CategoryExcelVo.class).sheet("分类数据").doWrite(categoryExcelVos);
    }
    @SneakyThrows


    @Override
    public void importData(MultipartFile file) {

        EasyExcel.read(file.getInputStream(), CategoryExcelVo.class, new CategoryExcelListener(categoryMapper)).sheet("分类数据").doRead();
    }


}

